package com.whksoft.mymapplugin.Listener;

import com.whksoft.mymapplugin.API.Event.PaymentCanceledEvent;
import com.whksoft.mymapplugin.utils.CancelReason;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.NamespacedKey;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.Plugin;

import static com.whksoft.mymapplugin.utils.flagUtils.haveQRFlag;

/**
 * 检测玩家死亡
 */
public class playerDead implements Listener {

    Plugin plugin;

    public playerDead(Plugin plugin) {
        this.plugin = plugin;
    }

    //玩家死亡之后清除扫码地图 取消支付
    @EventHandler(priority = EventPriority.HIGHEST)
    public void playerDeath(PlayerDeathEvent e) {
        // TODO: 2021/1/25 检测玩家死亡
        boolean value = e.getKeepInventory();
        if (!value) {
            for (ItemStack itemStack : e.getDrops()) {
                if (itemStack == null) continue;
                if (itemStack.getType() == Material.FILLED_MAP) {
                    NamespacedKey key = new NamespacedKey(plugin, "isQRCode");
                    ItemMeta itemMeta = itemStack.getItemMeta();
                    if (itemMeta == null) return;
                    if (haveQRFlag(key, itemStack)) {
                        PaymentCanceledEvent event = new PaymentCanceledEvent(e.getEntity().getPlayer(), CancelReason.PLAYER_DEAD);
                        //e.getEntity().sendMessage("您死亡了 取消支付！");
                        itemStack.setAmount(0);
                        Bukkit.getPluginManager().callEvent(event);
                    }
                }
            }
        } else {
            for (ItemStack itemStack : e.getEntity().getInventory()) {
                if (itemStack == null) continue;
                if (itemStack.getType() == Material.FILLED_MAP) {
                    NamespacedKey key = new NamespacedKey(plugin, "isQRCode");
                    ItemMeta itemMeta = itemStack.getItemMeta();
                    if (itemMeta == null) return;
                    if (haveQRFlag(key, itemStack)) {
                        PaymentCanceledEvent event = new PaymentCanceledEvent(e.getEntity().getPlayer(), CancelReason.PLAYER_DEAD);
                        //e.getEntity().sendMessage("您死亡了 取消支付！");
                        itemStack.setAmount(0);
                        Bukkit.getPluginManager().callEvent(event);
                    }
                }
            }
        }
    }
}
